package org.dxy.trigger.listener.process;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.common.eventbus.Subscribe;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.event.process.ProcessCreatedEvent;
import org.dxy.infrastructure.persistent.db.mybatispuls.po.query.ProcessViewPo;
import org.dxy.infrastructure.persistent.db.mybatispuls.service.ProcessViewService;
import org.dxy.trigger.listener.EventListener;
import org.springframework.stereotype.Component;

/**
 * 工序创建事件监听器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ProcessCreatedEventListener implements EventListener<ProcessCreatedEvent> {
    
    private final ProcessViewService processViewService;
    
    @Override
    @Subscribe
    public void onEvent(ProcessCreatedEvent event) {
        try {
            log.info("处理工序创建事件: {}", event);

            LambdaUpdateWrapper<ProcessViewPo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(ProcessViewPo::getId, event.processId())
                    .set(ProcessViewPo::getProcessCode, event.processCode())
                    .set(ProcessViewPo::getStatus, event.status());

            // 保存到读模型
            processViewService.update(lambdaUpdateWrapper);
            
            log.info("工序读模型保存成功, processId={}", event.processId());
        } catch (Exception e) {
            log.error("处理工序创建事件失败", e);
            throw new RuntimeException("处理工序创建事件失败", e);
        }
    }
}